package Classic150;

import java.util.HashSet;
import java.util.Set;

public class 快乐数 {

    public boolean isHappy(int n) {
        /*
            快慢双指针判断是否重复
         */
        int slow = n;
        int fast = getNext(n);
        while (fast != 1 && slow != fast) {
            slow = getNext(slow);
            fast = getNext(getNext(fast));
        }
        return fast == 1;

        /*
            用hashset判断是否重复
        */
        /*Set<Integer> set = new HashSet<>();
        while (n != 1 && !set.contains(n)) {
            set.add(n);
            n = getNext(n);
        }
        return n == 1;*/
    }

    private int getNext(int n) {
        int sum = 0;
        while (n > 0) {
            int number = n % 10;
            n = n / 10;
            sum += number * number;
        }
        return sum;
    }
}
